$(document).ready(function () {
    initSize();
    //获取当前时间
    // $("#time").showCurrentTime();
})

/*初始化默认字体大小*/
function initSize() {
    //适应不同分辨率
    let fontSize;
    resize();
    window.onresize = resize;

    function resize() {

        let winW = window.innerWidth;

        if (winW < 1366) {
            winW = 1366;
        }
        fontSize = winW / 1920 * 100
        document.getElementsByTagName('html')[0].style.cssText = "font-size:" + fontSize + "px";
    }

    // let userInfo = JSON.parse(localStorage.getItem("isLogin"));
    // $('#userName').html(userInfo.name);
}


// 初始化菜单

initMenu = () => {

    Ajax('/menu/auth', callback);

    function callback(res) {
        if (res.message == 'OK') {
            var data = res.result
            var str = `<div class="header-tab-item" data-type="1" data-url="index"><img
            src="../static/img/icon4.png">火灾分析研判</div>`

            data.forEach(e => {

                if (e.name == '后台管理') {
                    $('.back_menu').css('display', 'flex')
                }

                if (e.id == 'ca0ec71b267242c39a2aaaac50f8aac8') {
                    str = str + `<div class="header-tab-item" data-type="1" data-url="statistics"><img
                src="../static/img/icon5.png">火灾分析统计</div>`
                }
                if (e.id == 'af266f886a354c75af66f3c8d0fed671') {
                    str = str + `<div class="header-tab-item" data-type="1" data-url="casualtiesReport"><img
                src="../static/img/icon6.png">伤亡财产损失汇报</div>`
                }

                if (e.id == '430a024b78c341b9a5e2482d07cf63e1') {
                    str = str + `<div class="header-tab-item header-tab-parent" data-type="2">
                    <img src="../static/img/icon7.png">研判报告
                    <div class="header-tab-children" style="display: none;">`

                    data.forEach(e1 => {
                        if (e1.pId == '430a024b78c341b9a5e2482d07cf63e1') {
                            str = str + `<div class="tab-children" data-url="${e1.path.substring(0, e1.path.length - 5)}"><img src="../static/img/icon15.png">${e1.name}
                        </div>`
                        }
                    })
                    str = str + `</div></div>`
                }

                if (e.id == 'e4fb7010d4c84e61ae71cb38c3cd55ce') {
                    str = str + `<div class="header-tab-item header-tab-parent" data-type="2">
                    <img src="../static/img/icon17.png">消防监督
                    <div class="header-tab-children" style="display: none;">`

                    data.forEach(e1 => {
                        if (e1.pId == 'e4fb7010d4c84e61ae71cb38c3cd55ce') {
                            str = str + `<div class="tab-children" data-url="${e1.path.substring(0, e1.path.length - 5)}"><img src="../static/img/icon15.png">${e1.name}
                        </div>`
                        }
                    })
                    str = str + `</div></div>`
                }

                if (e.id == '10804a1250244e9e9c8a07d23ba91e04') {
                    str = str + `<div class="header-tab-item header-tab-parent" data-type="2">
                <img src="../static/img/icon8.png">综合数据管理
                <div class="header-tab-children" style="display: none;">`

                    data.forEach(e1 => {
                        if (e1.pId == '10804a1250244e9e9c8a07d23ba91e04') {
                            str = str + `<div class="tab-children" data-url="${e1.path.substring(0, e1.path.length - 5)}"><img src="../static/img/icon15.png">${e1.name}
                        </div>`
                        }
                    })
                    str = str + `</div></div>`

                }

            });


            $('.header-tab').empty().append(str)
            // 菜单切换
            $('.header-tab-item').click(function (e) {
                $(e.currentTarget).addClass('active').siblings().removeClass('active');


                if ($(e.currentTarget).data().type == 2) {
                    $(e.currentTarget).find('.header-tab-children').toggle()
                } else if ($(e.currentTarget).data().type == 1) {
                    window.location.href = "../html/" + $(e.currentTarget).data().url + ".html";
                }
            })
            $('.tab-children').click(function (e) {
                e.stopPropagation()

                if ($(e.currentTarget).data().url != "xxx") {
                    window.location.href = "../html/" + $(e.currentTarget).data().url + ".html";
                }
            })

            let curl = (window.location.href.split("/html/"))[1].split('.')[0]

            if ($('.header-tab-item[data-url=' + curl + ']').data() == undefined) {
                $('.tab-children[data-url=' + curl + ']').parent().parent().addClass('active')
            } else {
                $('.header-tab-item[data-url=' + curl + ']').addClass('active')
            }


        }
    }




}

$('.back_menu').click(function () {

    window.location.href = "../html/b_Management.html";

})


/*判断字段是否为空或者*/
function checkNullOrEmpty(field) {

    if (field == null || field === "") {
        return ''
    } else {
        return field
    }

}

/**/

function logout() {
    layer.confirm('确定退出系统？', {
        btn: ['确定', '取消'] //按钮
    }, function () {
        loginOut();
    });
}

function loginOut() {
    $.ajax({
        url: '/rest/fireanalysis/logout',
        type: "post",
        contentType: "application/json",
        success: function (result) {
            localStorage.setItem('sessionId', "");


            window.location.href = "../html/login.html";
        },
        error: function (result) {
            localStorage.setItem('sessionId', "");
            window.location.href = "../html/login.html";
        }
    })
}


function Judgeidentity() {
    var isLogin = localStorage.getItem('sessionId');
    if (isLogin == null || isLogin == "") {
        window.location.href = "../html/login.html";
    }
}


function ajaxPrefix() {
    return '/rest/fireanalysis'
}

function Ajax(url, callBack, parms, type) {
    $.ajax({
        url: ajaxPrefix() + url,
        type: type ? type : 'get',
        data: parms ? JSON.stringify(parms) : '',
        headers: {
            SessionId: JSON.parse(localStorage.getItem('sessionId'))
        },
        contentType: "application/json",
        success: function (result) {

            callBack(result);

        }
    });
}

function AjaxRequest(url, callBack, parms, type, async) {
    $.ajax({
        url: ajaxPrefix() + url,
        type: type ? type : 'get',
        data: parms ? JSON.stringify(parms) : '',
        traditional: true,
        headers: {
            SessionId: JSON.parse(localStorage.getItem('userInfo')).sessionId
        },
        async: false,
        contentType: "application/json",
        success: function (result) {
            callBack(result);
        }
    });
}


var compare = function (prop) {
    return function (obj1, obj2) {
        var val1 = obj1[prop];
        var val2 = obj2[prop];
        if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
            val1 = Number(val1);
            val2 = Number(val2);
        }
        if (val1 < val2) {
            return -1;
        } else if (val1 > val2) {
            return 1;
        } else {
            return 0;
        }
    }
}



// 屏幕截图
function screenshot() {
    setTimeout(() => {
        layer.msg('正在抓取屏幕信息，请稍后...');
    }, 300);

    // 截图整个页面
    html2canvas(document.body, {
        scale: 2, // 提高分辨率
        useCORS: true, // 允许加载跨域图片
    })
        .then(canvas => {
            const imgData = canvas.toDataURL('image/png'); // 转为Base64
            const link = document.createElement('a');
            link.href = imgData;
            link.download = '智慧物流数字看板' + new Date().getTime() + '.png';
            link.click();
        });
}



/**
 * 获取子菜单
 * @function workStationMenu
 * @param {类型} type - 1:一体化 2:物业 3:综合管理
 * @returns
*/
function workStationMenu(type) {

    switch (type) {
        case 1:
            var menuList = [{
                name: '物业管理',
                path: 'propertyChart'
            },
            {
                name: '九小场所管理',
                path: '9SmallPlaces'
            },
            {
                name: '协作机制预案',
                path: '',
                children: [{
                    name: '预案模版',
                    path: 'planTemplate'
                },
                {
                    name: '数字化预案',
                    path: 'digitalPlan'
                }
                ]
            },
            {
                name: '消防巡查',
                path: '2xxx.html'
            },
            {
                name: '企业自查自纠',
                path: '2xxx.html'
            },
            {
                name: '企业维保记录',
                path: '2xxx.html'
            },
            {
                name: '安全会议纪要',
                path: '2xxx.html'
            },
            {
                name: '动火管理',
                path: '2xxx.html'
            },
            {
                name: '举报投诉',
                path: '2xxx.html'
            },

            ]
            break;
        case 2:
            var menuList = [
                {
                    name: '物业总览',
                    path: 'propertyChart'
                },
                {
                    name: '物业管理',
                    path: 'propertymanage'
                },
                {
                    name: '企业自查',
                    path: 'selfCheck'
                },
                {
                    name: '街道巡查',
                    path: 'streetCheck'
                },
                {
                    name: '问题整改',
                    path: 'correction'
                },
                {
                    name: '街道复查',
                    path: 'doubleCheck'
                },
                {
                    name: '遗留问题',
                    path: 'remainProblems'
                },
                {
                    name: '违规行为告知书',
                    path: 'violationNotice'
                },
            ]
            break;
        case 3:
            var menuList = [
                {
                    name: '重点单位',
                    path: 'keyunit'
                },
                {
                    name: '天然水源',
                    path: 'naturalWater'
                },
                {
                    name: '风险点',
                    path: 'risk'
                },
                {
                    name: '快速处置队',
                    path: 'quickteam'
                },
                {
                    name: '微型消防站',
                    path: 'ministation'
                },

            ]
            break;
        default:
            break;
    }

    $('.header-menu').empty().append(menuList.reduce((x, y) => {

        let path = y.path;


        if (y.name == '协作机制预案') {
            let active = window.location.href.indexOf(path) > -1 ? 'active' : ''
            var str = ''
            y.children.forEach(e => {
                active = window.location.href.indexOf(e.path) > -1 ? 'active' : ''
                str += `<div class="tab-children" data-url="${e.path}">
                            <img src="../static/img/icon15.png" alt="" >${e.name}</img>
                        </div>`
            })
            return x + `
            <div class="h-m-item ${active}"  data-type="2">
                <img src="../static/img/workstation/${y.name}.png" alt="">${y.name}</img>
                <div class="header-tab-children" style="display: none;">
                    ${str}
                </div>
            </div>
            `
        } else {
            let active = window.location.href.indexOf(path) > -1 ? 'active' : ''
            return x + `
        <div class="h-m-item ${active}"  data-type="1" data-url="${y.path}"><img onerror="this.src='../static/img/workstation/default.png'" src="../static/img/workstation/${y.name}.png" alt="">${y.name}</div>
        `
        }
    }, ''))

    // 菜单切换
    $('.h-m-item').click(function (e) {
        $(e.currentTarget).addClass('active').siblings().removeClass('active');

        if ($(e.currentTarget).data().type == 2) {
            $(e.currentTarget).find('.header-tab-children').toggle()
        } else if ($(e.currentTarget).data().type == 1) {
            window.location.href = "../html/" + $(e.currentTarget).data().url + ".html";;
        }
    })
    $('.tab-children').click(function (e) {
        e.stopPropagation()
        window.location.href = "../html/" + $(e.currentTarget).data().url + ".html";;
    })
}



// 数据导入

$('.s-btn.bth-import').click(function (e) {
    $("#importFilePath").attr("value", '');
    $("#importFile").click();
})


function importFile(files, url) {
    $("#importFilePath").attr("value", $("#importFile").val());
    var uploadFile = $("#importFile").val();
    if (uploadFile == '') {
        layer.msg("请选择导入文件!");
    } else if (uploadFile.lastIndexOf(".xls") < 0) {
        layer.msg("只能上传.xls的Excel文件!");
    } else {
        let data = new FormData();
        data.append("file", $('#importFile')[0].files[0])

        $.ajax({
            url: ajaxPrefix() + url,
            type: 'post',
            data: data,
            dataType: "json",
            cache: false, headers: {
                SessionId: JSON.parse(localStorage.getItem('sessionId'))
            },
            processData: false,
            contentType: false,
            success: function (result) {
                if (result.status == 200) {
                    layer.msg('导入成功!')
                    queryTableData();
                } else {
                    $("#importFile").val('')
                    layer.msg(result.result + '!')
                }
                $("#importFilePath").val('');
            }
        })

    }

}


function resDel(id, url) {
    layer.confirm('确认是否删除?', {
        btn: ['确认', '取消'] //按钮
    }, function () {
        AjaxRequest(url + '?id=' + id, callBack)
        function callBack(result) {
            if (result.status == 200) {
                layer.msg('删除成功 !')
                queryTableData()
            } else {
                layer.msg('删除失败 !')
            }
        }
    });
}

// 扁平数据转树形结构函数
function flatToTree(flatData, idKey = 'id', parentKey = 'pId', childrenKey = 'children') {
    const nodeMap = {};
    flatData.forEach(node => {
        nodeMap[node[idKey]] = { ...node, [childrenKey]: [] };
    });

    const tree = [];
    flatData.forEach(node => {
        const parentId = node[parentKey];
        const currentNode = nodeMap[node[idKey]];

        if (parentId === 0 || !nodeMap[parentId]) {
            tree.push(currentNode);
        } else {
            nodeMap[parentId][childrenKey].push(currentNode);
        }
    });

    return tree;
}


// 图片预览
previewPhoto = (url) => {
    layer.photos({
        photos: {
            "data": [
                {
                    "src": url,
                }

            ]

        },
        footer: false
    });
}


// 导出
function postExport(url, data) {

    data.sessionId = JSON.parse(localStorage.getItem('sessionId'))

    // 创建隐藏表单
    const $form = $('<form>')
        .attr({
            'method': 'post',
            'action': url,
        });

    // 添加数据字段
    $.each(data, function (key, value) {
        $('<input>')
            .attr({
                'name': key,
                'value': value || ''
            })
            .css('display', 'none')
            .appendTo($form);
    });

    // 提交表单
    $form.appendTo('body').submit();
    $form.remove();
}



/**
 * 模版字符串渲染
 * @function renderTpl
 * @param {object} data - 渲染的数据
 * @param {string} r1 - 模版id
 * @param {string} r2 - 插入模版box的id
 * @returns
*/

function renderTpl(data, r1, r2) {


    let tpl = $(r1).html();
    laytpl(tpl).render(data, function (html) {
        $(r2).html(html);
    });
}



// 用户修改密码
changePwd = () => {
    layer.prompt({
        title: '请输入新密码'
        , formType: 1
        , success: function (layero, index) {
            var promptInput = layero.find('input');
            promptInput.attr('autocomplete', 'off');
        }
    },
        function (value, index, elem) {

            if (value === '') return elem.focus();

            passwordOne = value;

            layer.close(index);

            layer.prompt({
                title: '请确认新密码'
                , formType: 1
                , success: function (layero, index) {
                    var promptInput = layero.find('input');
                    promptInput.attr('autocomplete', 'off');
                }
            },
                function (valueNew, indexNew) {

                    if (valueNew === '') return elem.focus();

                    passwordTwo = valueNew;
                    layer.close(indexNew);
                    if (passwordOne == passwordTwo) {

                        Ajax('/user/password/update', callback,
                            {
                                id: JSON.parse(localStorage.getItem("userInfo")).userId,
                                passwordOne: passwordOne,
                                passwordTwo: passwordTwo,
                            }
                            , 'post');
                        function callback(res) {

                            if (res.status == "400") {
                                layer.msg(res.result)
                            } else {
                                layer.msg('修改成功', { icon: 1, time: 2000 });
                                loginOut()
                            }

                            layer.close(index);

                        }

                    } else {
                        layer.msg('两次密码输入不一致，请重新设置')
                    }

                });

        });
}


// 鼠标移入提示

$('.btn-tips').hover(
    function () { // 鼠标移入时触发
        var tipContent = $(this).data('tip');
        tipIndex = layer.tips(tipContent, this, {
            tips: [3, '#2273a1'], // 提示方向和控制背景色
            time: 0 // 不自动关闭
        });
    },
    function () { // 鼠标移出时触发
        layer.close(tipIndex); // 关闭提示层
    }
);